import { render, screen, waitFor } from '@testing-library/react';
import { rest } from 'msw';
import News from '../News';
import { server } from '../../../mocks/server';
describe('<Users />', () => {
test('should component show error message', async () => {
server.resetHandlers(
rest.get('http://localhost:5000/news', (req, res, ctx) => {
return res(ctx.status(400));
})
);
render(<News />);
await waitFor(async () => {
const error = await screen.findByText(/SERVER ERROR/i);
expect(error).toBeInTheDocument();
});
});
});
我們可以使用waitFor的方式等待所有非同步事件完成並觸發callback,解釋如下
waitFor
may run the callback a number of times until the timeout is reached. Note that the number of calls is constrained by the timeout
and interval
options.
This can be useful if you have a unit test that mocks API calls and you need to wait for your mock promises to all resolve.